package interficie;

import java.awt.Choice;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

/**
 * Created by Rafael Simon Garcia on 11/12/13.
 */


public class ModifyTaskElementsView extends JFrame{

    private CtrlInterficie controller;

    private ArrayList<String> machineElements;
    private String task;
    private Choice elementsDropDown = null;
    private DefaultTableModel dm = TableModel();
    private JTable t = new JTable(dm);

    public ModifyTaskElementsView(CtrlInterficie c, String t, ArrayList<String> l) {
    	getContentPane().setBackground(new Color(30, 144, 255));
        this.controller = c;
        this.task = t;
        this.machineElements = l;
        InitializeWindow();
        
    }

    public void ResetTaskElementsDropDownMenu(ArrayList<String> elems){
        for(String st : elems) elementsDropDown.add(st);
    }

    private void InitializeWindow(){
        setBackground(new Color(0, 153, 255));
        getContentPane().setLayout(null);
        setBounds(100, 100, 668, 531);

        
        JTable elementsTable = ElementsTable(dm);

        getContentPane().add(TableScrollPanel(elementsTable));

        getContentPane().add(AddElementLabel());
        getContentPane().add(SelectExistingElementLabel());
        getContentPane().add(CreateElementLabel());
        getContentPane().add(WeirdLabel());
        getContentPane().add(ElementsConstraintLabel());
        getContentPane().add(ImportantLabel());

        getContentPane().add(CreateElementButton());

        JButton saveButton  = SaveElementsInTaskButton();

        getContentPane().add(AddElementToTaskButton(saveButton, ElementsDropDownMenu(), elementsTable, dm));

        getContentPane().add(ElementsDropDownMenu());
        getContentPane().add(saveButton);

        getContentPane().add(CancelButton());

    }

    private JScrollPane TableScrollPanel(JTable t) {
        JScrollPane sp_contenedor = new JScrollPane();
        sp_contenedor.setBounds(0, 383, 668, 137);
        sp_contenedor.setBackground(new Color(0, 102, 204));
        sp_contenedor.setViewportView(t);
        sp_contenedor.setVisible(true);
        return sp_contenedor;
    }

    private Action DeleteAction(){
        return new AbstractAction()
        {
            public void actionPerformed(ActionEvent e)
            {
                JTable table = (JTable)e.getSource();
                int modelRow = Integer.valueOf( e.getActionCommand() );
                int result =
                        JOptionPane.showConfirmDialog(
                                null,
                                "Seguro que desea eliminar esta subtarea?",
                                "Eliminar una subtarea",
                                JOptionPane.YES_NO_OPTION);

                if(result == JOptionPane.YES_OPTION) {
                    ((DefaultTableModel)table.getModel()).removeRow(modelRow);
                }
            }
        };
    }

    private JTable ElementsTable(DefaultTableModel dm){
        
        t.setFont(new Font("Tahoma", Font.BOLD, 13));
        t.setBackground(new Color(153, 204, 255));
        t.setRowHeight(30);

        ButtonRender renderer2 = new ButtonRender(t, DeleteAction(), 3);
        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);

        t.getColumn("T�tulo").setCellRenderer(renderer);
        t.getColumn("Descripci�n").setCellRenderer(renderer);
        t.getColumn("Coste").setCellRenderer(renderer);
        t.getColumn("X").setCellRenderer(renderer2);

        t.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        TableColumn tc;
        tc = t.getColumnModel().getColumn(0);
        tc.setPreferredWidth(300);
        tc = t.getColumnModel().getColumn(1);
        tc.setPreferredWidth(280);
        tc = t.getColumnModel().getColumn(2);
        tc.setPreferredWidth(50);
        tc = t.getColumnModel().getColumn(3);
        tc.setPreferredWidth(38);

        for(String a : machineElements) dm.addRow(controller.getInfoSubtarea(a));

        return t;
    }

    private DefaultTableModel TableModel(){
        DefaultTableModel dm = new DefaultTableModel(0,0);
        dm.setColumnIdentifiers(new String[]{"T�tulo", "Descripci�n", "Coste","X"});
        return dm;
    }

    private Choice ElementsDropDownMenu() {
        if(elementsDropDown != null) return elementsDropDown; //if already initialized return the variable

        elementsDropDown = new Choice();
        elementsDropDown.setBounds(61, 190, 193, 20);
        ResetTaskElementsDropDownMenu(controller.getSubtareas());

        return elementsDropDown;
    }

    private JLabel WeirdLabel() {
        JLabel label = new JLabel("\u00D3");
        label.setFont(new Font("Tahoma", Font.BOLD, 16));
        label.setBounds(323, 177, 21, 36);
        return label;
    }

    private JButton CancelButton() {
        JButton b_cancelar = new JButton("Cancelar");
        b_cancelar.setBounds(105, 321, 89, 23);
        b_cancelar.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) { 
            	controller.activar();
                dispose();
            }
        });
        return b_cancelar;
    }

    private JButton SaveElementsInTaskButton() {
        JButton button =  new JButton("Guardar");
        button.setBounds(432, 321, 89, 23);
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                JOptionPane.showMessageDialog(null, "Se han modificado con �xito las subtareas", "Lista de Subtareas Modificada", JOptionPane.INFORMATION_MESSAGE);
                recogerDatos();
                controller.modificarTarea(task, task, controller.getInfoTarea(task).get(1).toString(), machineElements);
                controller.modificarTarea(task);
                controller.activar();
                dispose();
            }
        });
        if(machineElements.size() > 0) button.setEnabled(true);
        else button.setEnabled(false);
        return button;
    }

    private JButton CreateElementButton() {
        JButton b_crear = new JButton("Crear Nueva");
        b_crear.setBounds(422, 190, 113, 23);
        b_crear.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) { controller.crearSubtarea(); }
        });
        return b_crear;
    }

    private JButton AddElementToTaskButton(final JButton b, final Choice e, final JTable t, final DefaultTableModel dm) {
        JButton button = new JButton("A\u00F1adir");
        button.setBounds(105, 228, 89, 23);
        button.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    boolean add = true;

                    for (int i = 0; i < t.getRowCount(); ++i) {
                        String tabla = t.getValueAt(i, 0).toString();
                        String choic = e.getSelectedItem();
                        if (tabla.equals(choic)) {
                            add = false;
                            break;
                        }
                    }

                    if(add){
                        Vector<Object> data = controller.getInfoSubtarea(e.getSelectedItem());
                        dm.addRow(data);
                        machineElements.add(data.get(0).toString());
                        b.setEnabled(true);
                    }
                }
        });
        return button;
    }

    private JLabel ImportantLabel() {
        JLabel label = new JLabel("[IMPORTANTE]");
        label.setForeground(new Color(0, 0, 128));
        label.setBackground(Color.PINK);
        SetLabelFont(label, Font.BOLD | Font.ITALIC, 12);
        label.setBounds(105, 84, 100, 20);
        return label;
    }

    private JLabel SelectExistingElementLabel() {
        JLabel label = new JLabel("Selecciona una Subtarea Existente");
        SetLabelFont(label, Font.BOLD, 13);
        label.setHorizontalAlignment(SwingConstants.CENTER);
        label.setBounds(46, 158, 226, 14);
        return label;
    }

    private JLabel AddElementLabel() {
        JLabel label;

        label = (this.task != null) ? new JLabel(this.task + " - Modificar Subtareas") : new JLabel("null - Modificar Subtareas");

        SetLabelFont(label, Font.BOLD, 15);
        label.setHorizontalAlignment(SwingConstants.CENTER);
        label.setBounds(0, 43, 668, 14);
        return label;
    }

    private JLabel CreateElementLabel() {
        JLabel label = new JLabel("Crea una Subtarea nueva");
        label.setHorizontalAlignment(SwingConstants.CENTER);
        SetLabelFont(label, Font.BOLD, 13);
        label.setBounds(368, 158, 226, 14);
        return label;
    }

    private JLabel ElementsConstraintLabel() {
        JLabel label = new JLabel("Una tarea debe contener al menos una Subtarea");
        label.setForeground(new Color(25, 25, 112));
        SetLabelFont(label, Font.BOLD | Font.ITALIC, 12);
        label.setBounds(215, 84, 320, 20);
        return label;
    }

    private void SetLabelFont(JLabel l, int type, int size) { l.setFont(new Font("Tahoma", type, size)); }
    
    private void recogerDatos() {
            System.out.println("anadir subtareas guardarsubtareas");
            machineElements.clear();
            for(int i = 0; i < t.getRowCount(); ++i){
                    machineElements.add(t.getValueAt(i, 0).toString());
            }
    }
}
